---
import { client, getContentGroupId } from "virtual:vrite";
import type { Client, JSONContent } from "../api";
import Node from "./node.astro";

interface Props {
  contentPieceId?: string;
  content?: JSONContent;
  slug?: string;
  variant?: string;
}

let content: JSONContent | null = null;

if (Astro.props.content) {
  content = Astro.props.content;
} else {
  let contentPieceId = Astro.props.contentPieceId;

  if (!contentPieceId && Astro.props.slug) {
    const contentPieces = await (client as Client).contentPieces.list({
      contentGroupId: getContentGroupId(),
      slug: Astro.props.slug
    });
    if (contentPieces[0]) {
      contentPieceId = contentPieces[0].id;
    }
  }

  if (contentPieceId) {
    const contentPiece = await (client as Client).contentPieces.get({
      id: contentPieceId,
      content: true,
      description: "text",
      variant: Astro.props.variant
    });

    content = contentPiece.content;
  }
}
---

{content && <Node {...content} />}
